<?php

use App\Exceptions\BobException;


/**
 * 验证是否是中国手机号.
 *
 * @param string $number
 * @return bool
 */
function validateChinaPhoneNumber(string $number): bool
{
    return (bool)preg_match('/^(\+?0?86\-?)?1[3-9]\d{9}$/', $number);
}

/**
 * 验证用户名是否合法.
 *
 * @param string $username
 * @return bool
 */
function validateUsername(string $username): bool
{
    return (bool)preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $username);
}

/**
 * @param string $message
 * @param int $code
 * @param int $StatusCode
 * @throws BobException
 * @author Bob(bobcoder@qq.com)
 */
function return_bob(string $message, int $code = 0, $StatusCode = 400)
{
    throw new App\Exceptions\BobException($message, $code, $StatusCode);
}

/**
 * 将中文、英文、数字切割
 *
 * @param $str
 * @return array[]|false|string[]
 * @author Bob(bobcoder@qq.com)
 */
function bobPregSplit($str): array
{
    return preg_split("/([0-9]+)/", $str, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
}

/**
 * Get user login field.
 *
 * @param string $login
 * @param string $default
 * @return string
 * @author BobCoder <bob@bobcoder.cc>
 */
function username(string $login, string $default = 'id'): string
{
    $map = [
        'email' => filter_var($login, FILTER_VALIDATE_EMAIL),
        'phone' => validateChinaPhoneNumber($login),
        'username' => validateUsername($login),
    ];

    foreach ($map as $field => $value) {
        if ($value) {
            return $field;
        }
    }

    return $default;
}

/**
 * 随机字符串
 *
 * @param $n
 * @return string
 * @author Bob(bobcoder@qq.com)
 */
function getName($n = 16)
{

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $n; $i++) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }

    return $randomString;
}


/**
 * 生成菜单树
 * @param $list
 * @param $pid
 * @return array
 */
function generateRuleTree($list, $pid)
{
    $tree = [];
    foreach ($list as $row) {
        if ($row['pid'] === $pid) {
            $children = generateRuleTree($list, $row['id']);
            $row['children'] = $children ?? [];

            $tree[] = $row;
        }
    }

    return $tree;
}

/**
 * 生成菜单树
 * @param $list
 * @param $pid
 * @return array
 */
function generateRuleTree2($list, $pid)
{
    $tree = [];
    foreach ($list as $row) {
        if ($row['pid'] === $pid) {
            $row = [
                'id' => $row['id'],
                'label' => $row['title'],
                'pid' => $row['pid'],
                'path' => $row['name'],
                'icon' => $row['icon'],
                'menu' => $row['menu']
            ];

            $children = generateRuleTree2($list, $row['id']);
            if (!empty($children)) {
                $row['children'] = $children;
            }

            $tree[] = $row;
        }
    }

    return $tree;
}

function checkPermission($path, $isPreg = false)
{
    $loginInfo = session('loginInfo');
    $rules = $loginInfo['rules'] ?? [];

    if (session('loginInfo.admin_id') === 1) return true;

    if (empty($rules)) {
        return false;
    }

    if (!$isPreg) $path = preg_replace('/(^\/)|(\/$)/', '', $path);

    foreach ($rules as $value) {
        if (!$isPreg && ($path === $value)) {
            return true;
        }

        if ($isPreg && preg_match($path, $value)) {
            return true;
        }
    }

    return false;
}

/**
 * 检查密码
 *
 * @param \App\Models\User $user
 * @param $password
 * @return bool
 * @author: Bob(bobcoder@qq.com)
 */
function checkPassword(\App\Models\User $user, $password)
{
    $row = $user->makeVisible(['password'])->toArray();
    if (empty($row)) return false;

    if (password_verify($password, $row['password'])) {
        return true;
    }

    return false;
}

/**
 * 数据导出到excel(csv文件)
 * @param $fileName
 * @param array $tileArray
 * @param array $dataArray
 */
function export_excel($fileName, $tileArray = [], $dataArray = [])
{
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', 0);
    ob_end_clean();
    ob_start();
    header("Content-Type: text/csv");
    header("Content-Disposition:filename=" . $fileName);
    $fp = fopen('php://output', 'w');
    fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));// 转码 防止乱码(比如微信昵称)
    fputcsv($fp, $tileArray);
    $index = 0;
    foreach ($dataArray as $item) {
        if ($index == 1000) {
            $index = 0;
            ob_flush();
            flush();
        }
        $index++;
        fputcsv($fp, $item);
    }
    ob_flush();
    flush();
    ob_end_clean();
}

/**
 * 生成邀请码.
 * @return string
 * @author: BobCoder
 */
function generateInviteCode()
{
    $code = substr(str_shuffle('ZXCVBNMLPOIUYTREWQASDFGHJK'), 0, mt_rand(1, 5));

    return substr(str_shuffle('1234567890'), 0, 6 - strlen($code)) . $code;
}


/**
 * 是否是emoji.
 *
 * @param $s
 * @return bool
 * @author: hh
 */
function isEmoji($s)
{
    $len = mb_strlen($s);

    for ($i = 0; $i < $len; $i++) {
        $word = mb_substr($s, $i, 1);
        if (strlen($word) > 3) {
            return true;
        }
    }

    return false;
}

/**
 * 获取汉子首字母.
 *
 * @param $str
 * @return null|string
 * @author: BobCoder
 */
function getFirstCharter($str)
{
    if (empty($str)) {
        return null;
    }

    if (isEmoji($str)) {
        return '#';
    }

    $fchar = ord($str{0});

    if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
    $s1 = iconv('UTF-8', 'gb2312', $str);
    $s2 = iconv('gb2312', 'UTF-8', $s1);
    $s = $s2 == $str ? $s1 : $str;
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if ($asc >= -20319 && $asc <= -20284) return 'A';
    if ($asc >= -20283 && $asc <= -19776) return 'B';
    if ($asc >= -19775 && $asc <= -19219) return 'C';
    if ($asc >= -19218 && $asc <= -18711) return 'D';
    if ($asc >= -18710 && $asc <= -18527) return 'E';
    if ($asc >= -18526 && $asc <= -18240) return 'F';
    if ($asc >= -18239 && $asc <= -17923) return 'G';
    if ($asc >= -17922 && $asc <= -17418) return 'H';
    if ($asc >= -17417 && $asc <= -16475) return 'J';
    if ($asc >= -16474 && $asc <= -16213) return 'K';
    if ($asc >= -16212 && $asc <= -15641) return 'L';
    if ($asc >= -15640 && $asc <= -15166) return 'M';
    if ($asc >= -15165 && $asc <= -14923) return 'N';
    if ($asc >= -14922 && $asc <= -14915) return 'O';
    if ($asc >= -14914 && $asc <= -14631) return 'P';
    if ($asc >= -14630 && $asc <= -14150) return 'Q';
    if ($asc >= -14149 && $asc <= -14091) return 'R';
    if ($asc >= -14090 && $asc <= -13319) return 'S';
    if ($asc >= -13318 && $asc <= -12839) return 'T';
    if ($asc >= -12838 && $asc <= -12557) return 'W';
    if ($asc >= -12556 && $asc <= -11848) return 'X';
    if ($asc >= -11847 && $asc <= -11056) return 'Y';
    if ($asc >= -11055 && $asc <= -10247) return 'Z';

    return '#';
}

/**
 * 生成分类树
 *
 * @param $list
 * @param $pid
 * @return array
 * @link https://www.bobcoder.cc/
 * @Date 2019/5/21
 * @author Bob<bob@bobcoder.cc>
 */
function generateTree($list, $pid)
{
    $tree = [];
    foreach ($list as $row) {
        if ($row['pid'] === $pid) {
//            $row = [
//                'id' => $row['id'],
//                'name' => $row['name'],
//            ];
            $children = generateTree($list, $row['id']);
            if (!empty($children)) {
                $row['children'] = $children;
            }
            $tree[] = $row;
        }
    }
    return $tree;
}

/**
 * @param $password
 * @return bool|string
 * @author   Bob<bob@bobcoder.cc>
 * @link https://www.bobcoder.cc/
 * @Date  2019/8/19
 */
function createPassword($password)
{
    return password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);
}


/**
 * 生成订单号
 * @param string $prefix 前缀
 * @return string
 * @Author 姿势就是力量
 */
function createOrderNo($prefix = '')
{
    return $prefix . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/*
 * 验证用户密码
 * return bool
 */
function validatePassword($password)
{  // /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]/
    return (bool)preg_match('/(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?].{6,20}/', $password);
}

/*
 * 验证用户昵称  (有问题)
 * return bool
 */
function validateNickname($name)
{
    return (bool)preg_match('/^[\x80-\xff0-9a-zA-Z_\-]{4,20}$/', $name);

}

/*
 * 手机号码隐藏中间四位
 *  return string
 */
function ycPhone($str)
{
    return substr_replace($str, '****', 3, 4);
}

/*
 * 去除字符串中所有空格
 *  return string
 */
function trimall($str)
{
    return preg_replace('# #', '', $str);
}

/**
 * 时间判断
 * @param $the_time
 * @return false|string
 */
function time_tran($the_time)
{
    $now_time = time();
    $show_time = strtotime($the_time);
    $dur = $now_time - $show_time;
    if ($dur < 0) {
        return $the_time;
    } else {
        if ($dur < 60) {
            return $dur . '秒前';
        } else {
            if ($dur < 3600) {
                return floor($dur / 60) . '分钟前';
            } else {
                if ($dur < 86400) {
                    return floor($dur / 3600) . '小时前';
                } else {
                    if ($dur < 259200) {//3天内
                        return floor($dur / 86400) . '天前';
                    } else {
                        return date('Y-m-d', $show_time);
                    }
                }
            }
        }
    }
}


/**
 * 字符串转换bool类型
 * @param string $val
 * @return bool|mixed
 * @author 姿势就是力量
 */
function is_true($val)
{
    $boolVal = (is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool)$val);
    return $boolVal === null ? false : $boolVal;
}


